<template>
  <div class="todo-list-container">
    <div class="todo-header">
      <h1>待办事项列表</h1>
      <div class="filter-buttons">
        <button 
          @click="currentFilter = 'all'" 
          :class="{ active: currentFilter === 'all' }"
          class="filter-btn"
        >
          全部
        </button>
        <button 
          @click="currentFilter = 'active'" 
          :class="{ active: currentFilter === 'active' }"
          class="filter-btn"
        >
          未完成
        </button>
        <button 
          @click="currentFilter = 'completed'" 
          :class="{ active: currentFilter === 'completed' }"
          class="filter-btn"
        >
          已完成
        </button>
      </div>
    </div>
    
    <div class="add-todo">
      <button @click="showAddForm = true" class="btn btn-add">
        添加待办事项
      </button>
    </div>
    
    <div v-if="loading" class="loading">
      加载中...
    </div>
    
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    
    <div v-else-if="filteredTodos.length === 0" class="empty-state">
      没有待办事项
    </div>
    
    <div v-else class="todo-items">
      <todo-item 
        v-for="todo in filteredTodos" 
        :key="todo.id" 
        :todo="todo"
        @update-status="updateTodoStatus"
        @edit="editTodo"
        @delete="confirmDelete"
      />
    </div>
    
    <div v-if="showAddForm" class="modal-overlay">
      <div class="modal">
        <todo-form 
          :is-edit="false" 
          @submit="addTodo" 
          @cancel="showAddForm = false"
        />
      </div>
    </div>
    
    <div v-if="showEditForm" class="modal-overlay">
      <div class="modal">
        <todo-form 
          :is-edit="true" 
          :todo="currentTodo" 
          @submit="updateTodo" 
          @cancel="showEditForm = false"
        />
      </div>
    </div>
    
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="modal delete-confirm">
        <h3>确认删除</h3>
        <p>确定要删除此待办事项吗？此操作不可撤销。</p>
        <div class="confirm-actions">
          <button @click="showDeleteConfirm = false" class="btn btn-cancel">取消</button>
          <button @click="deleteTodo" class="btn btn-delete">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TodoItem from './TodoItem.vue';
import TodoForm from './TodoForm.vue';
import api from '../services/api';

export default {
  name: 'TodoList',
  components: {
    TodoItem,
    TodoForm
  },
  data() {
    return {
      todos: [],
      currentFilter: 'all', // 'all', 'active', 'completed'
      loading: false,
      error: null,
      showAddForm: false,
      showEditForm: false,
      showDeleteConfirm: false,
      currentTodo: null,
      deleteId: null
    }
  },
  computed: {
    filteredTodos() {
      switch(this.currentFilter) {
        case 'active':
          return this.todos.filter(todo => todo.status === 0);
        case 'completed':
          return this.todos.filter(todo => todo.status === 1);
        default:
          return this.todos;
      }
    }
  },
  created() {
    this.fetchTodos();
  },
  methods: {
    async fetchTodos() {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await api.getAllTodos();
        this.todos = response.data.data || [];
        // 确保状态和优先级是数字
        this.todos.forEach(todo => {
          todo.status = Number(todo.status);
          todo.priority = Number(todo.priority);
        });
      } catch (err) {
        console.error('获取待办事项失败:', err);
        this.error = '获取待办事项失败，请稍后再试！';
      } finally {
        this.loading = false;
      }
    },
    
    async addTodo(todo) {
      try {
        await api.addTodo(todo);
        this.showAddForm = false;
        await this.fetchTodos();
      } catch (err) {
        console.error('添加待办事项失败:', err);
        alert('添加待办事项失败，请稍后再试！');
      }
    },
    
    editTodo(todo) {
      this.currentTodo = { ...todo };
      this.showEditForm = true;
    },
    
    async updateTodo(todo) {
      try {
        await api.updateTodo(todo);
        this.showEditForm = false;
        await this.fetchTodos();
      } catch (err) {
        console.error('更新待办事项失败:', err);
        alert('更新待办事项失败，请稍后再试！');
      }
    },
    
    async updateTodoStatus(id, status) {
      try {
        await api.updateTodoStatus(id, status);
        // 更新本地状态，避免重新获取
        const todo = this.todos.find(t => t.id === id);
        if (todo) {
          todo.status = status;
        }
      } catch (err) {
        console.error('更新状态失败:', err);
        alert('更新状态失败，请稍后再试！');
        await this.fetchTodos(); // 如果失败，重新获取数据
      }
    },
    
    confirmDelete(id) {
      this.deleteId = id;
      this.showDeleteConfirm = true;
    },
    
    async deleteTodo() {
      if (!this.deleteId) return;
      
      try {
        await api.deleteTodo(this.deleteId);
        this.showDeleteConfirm = false;
        await this.fetchTodos();
      } catch (err) {
        console.error('删除待办事项失败:', err);
        alert('删除待办事项失败，请稍后再试！');
      }
    }
  }
}
</script>

<style scoped>
.todo-list-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.todo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.todo-header h1 {
  margin: 0;
  color: #333;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.filter-btn {
  background-color: #f1f1f1;
  border: none;
  border-radius: 20px;
  padding: 8px 15px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.filter-btn:hover {
  background-color: #e0e0e0;
}

.filter-btn.active {
  background-color: #4285f4;
  color: white;
}

.add-todo {
  margin-bottom: 20px;
}

.btn-add {
  background-color: #34a853;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10px 16px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-add:hover {
  background-color: #2e9549;
}

.loading, .error, .empty-state {
  text-align: center;
  padding: 30px;
  border-radius: 8px;
  background-color: #f8f8f8;
  margin-top: 20px;
}

.error {
  color: #ea4335;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.delete-confirm {
  text-align: center;
}

.delete-confirm h3 {
  color: #ea4335;
}

.confirm-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.btn {
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.btn-cancel {
  background-color: #f1f1f1;
  color: #333;
}

.btn-delete {
  background-color: #ea4335;
  color: white;
}

.todo-items {
  margin-top: 20px;
}

@media (max-width: 600px) {
  .todo-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .filter-buttons {
    width: 100%;
    justify-content: space-between;
  }
}
</style> 